<template>
    <div id="box">
        <div id="box1" v-show="!visible">
            <el-container>
                <el-header>
                    <span>教师列表</span>
                    <span class="right">首页>教师列表</span>
                </el-header>
                <div class="headerbox">
                    <el-button type="primary" @click="del">删除选择</el-button>
                    <el-button type="success" @click="refresh">刷新</el-button>
                    <div class="dropdownBox">
                        <el-select v-model="value1" placeholder="请选择部门" @change="selectdep1" :plain="true">
                            <el-option
                                    v-for="item in options1"
                                    :key="item.value1"
                                    :label="item.label1"
                                    :value="item.value1"
                            >
                            </el-option>
                        </el-select>
                    </div>
                    <div class="dpmBox">
                        <el-input placeholder="请输入教师姓名" v-model="teachername" clearable></el-input>
                    </div>
                    <el-button type="primary" icon="el-icon-search" @click="query1">查询</el-button>
                    <el-button type="success" class="right" @click="add">新增教师</el-button>
                </div>
                <!--表格内容-->
                <el-main>
                    <div>
                        <el-table
                                ref="multipleTable"
                                :data="tableData"
                                tooltip-effect="dark"
                                style="width: 100%"
                                @selection-change="handleSelectionChange"
                        >
                            <el-table-column
                                    type="selection"
                                    style="width:2%">
                            </el-table-column>
                            <el-table-column
                                    prop="name"
                                    label="名字"
                                    style="width:2%">
                            </el-table-column>
                            <el-table-column
                                    prop="departmentName"
                                    label="部门"
                                    style="width:2%">
                            </el-table-column>
                            <el-table-column
                                    prop="sex"
                                    label="性别"
                                    style="width:2%"
                            >
                            </el-table-column>
                            <el-table-column
                                    prop="education"
                                    label="教育"
                                    style="width:5%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="phone"
                                    label="联系电话"
                                    style="width:10%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="email"
                                    label="电子邮件"
                                    style="width:35%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="entryTime"
                                    label="加入时间"
                                    style="width:10%"
                                    show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column
                                    prop="option"
                                    label="操作"
                                    style="width:20%"
                            >
                                <template slot-scope="scope">
                                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" class="opt">编辑
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-main>

            </el-container>
            <!--分页-->
            <el-pagination
                    :page-size="pageSize"
                    @current-change="handleCurrentChange"
                    layout="prev, pager, next"
                    :total="pagenum">
            </el-pagination>
            <!--page-size:每页显示条目个数
                pager-count：页码按钮的数量，当总页数超过该值时会折叠
                total	总条目数-->
        </div>
        <!--编辑页面-->
        <div id="box2" v-show="visible">
            <template>
                <div>
                    <el-container>
                        <el-header>
                            <span>修改教师信息</span>
                            <a class="right" @click="back" href="javascript:;">< 返回</a>
                        </el-header>
                        <div id="content">
                            <p class="jiben">基本信息</p>
                            <ul class="left">
                                <li>
                                    <p><span style="color: red">*</span>名字</p>
                                    <el-input v-model="name" placeholder="用户名" disabled></el-input>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>联系电话</p>
                                    <el-input v-model="phone" placeholder="联系电话"></el-input>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>所属部门</p>
                                    <el-select v-model="value" placeholder="请选择">
                                        <el-option
                                                v-for="item in options"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>出生日期</p>
                                    <el-date-picker
                                            v-model="birthday"
                                            align="right"
                                            disabled
                                            type="date"
                                            placeholder="年/月/日"
                                            :picker-options="pickerOptions">
                                    </el-date-picker>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>登录密码</p>
                                    <el-input v-model="password" placeholder="输入系统登录密码"></el-input>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>头像照片</p>
                                    <div slot="tip" class="el-upload__tip">
                                        单上传头像图片大小不能超过 2MB!,仅支持JPG、JPEG、PNG格式
                                    </div>
                                    <div id="upload">
                                        <el-upload
                                                class="avatar-uploader"
                                                action="/image"
                                                :show-file-list="false"
                                                :on-success="handleAvatarSuccess"
                                                :before-upload="beforeAvatarUpload"
                                                name="uploadFile"
                                        >
                                            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                        </el-upload>
                                    </div>
                                </li>
                            </ul>
                            <ul class="right">
                                <li>
                                    <p><span style="color: red">*</span>电子邮件</p>
                                    <el-input v-model="email" placeholder="电子邮件"></el-input>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>性别</p>
                                    <el-input v-model="sex" placeholder="性别" disabled></el-input>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>教育程度</p>
                                    <el-input v-model="education" placeholder="教育" disabled></el-input>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>入职时间</p>
                                    <el-date-picker
                                            v-model="entryTime"
                                            type="datetime"
                                            disabled
                                            placeholder="年/月/日">
                                    </el-date-picker>
                                </li>
                                <li>
                                    <p><span style="color: red">*</span>确认密码</p>
                                    <el-input v-model="confirm" placeholder="确认密码"></el-input>
                                </li>
                            </ul>
                        </div>
                    </el-container>
                    <div id="footBox">
                        <div id="footer">
                            <el-button type="info" @click="cancle">取消</el-button>
                            <el-button type="success" @click="preservation" :plain="true">保存</el-button>
                        </div>
                    </div>
                </div>
            </template>
        </div>

    </div>
</template>
<script>

    export default {
        name: "TeacherList",
        data: function () {
            return {
                teachername: '',//查询输入框教师名字
                imageUrl: "",//头像地址
                index: [],//存放id的数组
                delid: "",//删除数据的所有id
                pagenum: 0,//数据总条数（用于渲染页码）
                currentPage: 1,//默认页数是第一页
                name: '',//教师姓名
                phone: '',//联系方式
                birthday: '',//出生日期
                password: '',//登录密码
                email: '',//邮件
                sex: '',//性别
                education: '',//教育程度
                entryTime: '',//入职日期
                confirm: '',//确认密码
                fileList: [],//上传文件列表
                departement: '',//部门名称
                value: '',//弹出框部门的id
                value1: '',//首页部门id
                select: '',//下拉框中的数据
                tableData: [],//表格数据
                multipleSelection: [],//多选框选中的那条数据
                pickerOptions: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },//时间
                options: [],//部门
                options1: [],//存放部门名称和id
                visible: false,//弹框是否显示
                pageSize: 10,//每页展示10条数据

            }
        },
        methods: {
            handleAvatarSuccess(res, file) {
                this.imageUrl = res.data;
            },

            beforeAvatarUpload(file) {
                const isJPG = file.type === "image/jpeg";
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error("上传头像图片只能是 JPG 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            handlePreview(file) {
                console.log(file);
            },

            //添加教师
            add() {
                this.$router.push('/addTeacher');
            },

            //删除
            del() {
                if (this.multipleSelection.length == 0) {
                    this.$message({
                        message: '请先选择！',
                        type: 'warning'
                    });
                } else {
                    this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var data = this.multipleSelection;
                        for (var i = 0; i < data.length; i++) {
                            this.delid += data[i].id + ',';
                        }
                        this.delid = this.delid.substring(0, this.delid.length - 1);
                        console.log(this.delid);
                        this.$axios({
                            url: '/teacher/deleteTeacher',
                            params: {
                                ids: this.delid
                            }
                        }).then((res) => {
                            if (res.status == 200) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.xr();
                                location.reload();
                            }
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }

            },


            //点击编辑按钮
            handleEdit(index, row) {
                //渲染部门名称
                this.$axios({
                    url: '/teacher/findAllDepartment',
                    method: 'post'
                }).then((res) => {
                    var data = res.data.data;
                    if (this.options.length == 0) {
                        for (var i = 0; i < data.length; i++) {
                            this.options.push({value: data[i].id, label: data[i].departmentName})
                        }
                    }
                });
                //数据回显
                var id = row.id;
                sessionStorage.teacherId = id;
                this.$axios({
                    url: `/teacher/findTeacherById/${id}`,
                }).then((res) => {
                    var data = res.data.data;
                    if (data.sex) {
                        data.sex = '男'
                    } else {
                        data.sex = '女'
                    }
                    this.name = data.name;
                    this.phone = data.phone;
                    this.value = data.departmentName;
                    this.birthday = data.birthday;
                    this.password = data.password;
                    this.email = data.email;
                    this.sex = data.sex;
                    this.education = data.education;
                    this.entryTime = data.entryTime;
                    this.confirm = data.confirm;
                    this.imageUrl = data.image;
                    console.log(this.imageUrl);
                });
                this.visible = !this.visible;
            },

            //编辑界面中的返回按钮
            back() {
                this.visible = !this.visible
            },

            //取消
            cancle() {
                this.$confirm('检测到未保存的内容，是否在离开页面前保存修改？', '确认信息', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '保存',
                    cancelButtonText: '放弃修改'
                })
                    .then(() => {
                        this.preservation();
                    })
                    .catch(action => {
                        this.$message({
                            type: 'info',
                            message: action === 'cancel'
                                ? '放弃保存并离开页面'
                                : '停留在当前页面'
                        });
                        this.visible = !this.visible
                    });
            },

            //刷新
            refresh() {
                location.reload();
            },

            //手机号验证
            phoneyz() {
                var reg = /^1[3-9]\d{9}$/;
                if (!reg.test(this.phone)) {
                    this.$message.error('手机格式不正确，请重新输入！');
                    return false;
                } else {
                    return true;
                }
            },

            //邮箱验证
            emailyz() {
                //邮箱正则
                var emreg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                if (!emreg.test(this.email)) {
                    this.$message.error('邮箱格式不正确，请重新输入！');
                    return false;
                } else {
                    return true;
                }
            },

            //确认密码
            passyz() {
                //判断两次输入密码是否正确
                if (this.password != this.confirm) {
                    this.$message.error('两次输入密码不一致，请重新输入！');
                    return false;
                } else {
                    return true;
                }
            },

            //保存
            preservation() {
                var id = parseInt(sessionStorage.teacherId);
                //性别转换为0和1
                if (this.sex == '女') {
                    this.sex = 0
                } else if (this.sex == '男') {
                    this.sex = 1
                }
                //将部门名称转换位相应的部门id
                for (var i = 0; i < this.options1.length; i++) {
                    if (this.options1[i].label1 == this.value) {
                        this.value = this.options1.value1
                    }
                }
                if (this.phone == '' || this.value == undefined || this.email == '' || this.password == '' || this.confirm == '') {
                    this.$message.error('请填写完整信息');
                } else {
                    if (this.phoneyz()) {//判断电话号码
                        if (this.emailyz()) {//判断邮箱
                            if (this.passyz()) {//判断两次密码是否一致
                                this.$axios({
                                    url: '/teacher/update',
                                    method: 'POST',
                                    data: {
                                        id: id,
                                        name: this.name,
                                        sex: this.sex,
                                        phone: this.phone,
                                        departmentId: this.value,
                                        birthday: this.birthday,
                                        password: this.password,
                                        email: this.email,
                                        education: this.education,
                                        entryTime: this.entryTime,
                                        confirm: this.confirm,
                                        image: this.imageUrl
                                    }
                                }).then((res) => {
                                    if (res.data.code == 0) {
                                        this.$message({
                                            message: '修改成功',
                                            type: 'success'
                                        });
                                        location.reload();
                                    }
                                })
                            }
                        }
                    }
                }


            },

            //点击分页方法
            handleCurrentChange: function (currentPage) {
                this.currentPage = currentPage;
                if (!this.value1 && !this.teachername) {//如果没有选择部门名称查询或者姓名查询
                    this.xr();//渲染全部数据
                } else if (this.teachername && !this.value1) {//如果有教师名称,没有部门名称
                    this.query();
                } else if (this.value1 && !this.teachername) {//如果有部门名称,没有教师姓名
                    this.selectdep();
                } else if (this.value1 && this.teachername) {
                    this.slelectAll();
                }
            },

            //根据姓名查询
            query1() {
                this.currentPage = 1;
                this.query();
            },
            //根据姓名查询
            query() {
                if (this.value1 == '') {
                    this.$axios({
                        url: '/teacher/findTeacherByWhere',
                        params: {
                            page: this.currentPage,
                            limit: 10,
                            name: this.teachername,
                        }
                    }).then((res) => {
                        if (res.data.code == 0) {
                            this.pagenum = res.data.data.total;
                            var data = res.data.data.list;
                            this.sexToText(data);
                            this.tableData = data;
                        } else if (res.data.code == 50010) {
                            this.tableData = [];
                        }
                    })
                } else {
                    this.slelectAll();//同时根据姓名和部门查询
                }
            },

            //根据部门查询
            selectdep1() {
                this.currentPage = 1;
                this.selectdep()
            },
            //根据部门查询
            selectdep() {
                if (this.teachername == '') {
                    this.$axios({
                        url: '/teacher/findTeacherByWhere',
                        params: {
                            page: this.currentPage,//当前页码
                            limit: 10,
                            departmentId: this.value1,
                        }
                    }).then((res) => {
                        if (res.data.code == 0) {
                            var data = res.data.data.list;
                            this.sexToText(data);
                            this.tableData = data;
                            this.pagenum = res.data.data.total;//
                            this.$message({
                                message: '查询成功',
                                type: 'success'
                            });
                        } else if (res.data.code == 50010) {
                            this.tableData = [];
                        }
                    })
                } else {
                    this.slelectAll();
                }

            },

            //同时根据姓名和部门条件查询
            slelectAll() {
                this.$axios({
                    url: '/teacher/findTeacherByWhere',
                    params: {
                        page: this.currentPage,
                        limit: 10,
                        departmentId: this.value1,
                        name: this.teachername
                    }
                }).then((res) => {
                    if (res.data.code == 0) {
                        var data = res.data.data.list;
                        this.sexToText(data);
                        this.tableData = data;
                        this.pagenum = res.data.data.total;
                        this.$message({
                            message: '查询成功',
                            type: 'success'
                        });
                    } else if (res.data.code == 50010) {
                        this.tableData = [];
                    }
                })
            },

            //补零规则
            add0(m) {
                return m < 10 ? '0' + m : m
            },

            //将时间戳转换为日期格式
            format(shijianchuo) {
                //时间戳是整数，否则要parseInt转换
                var time = new Date(shijianchuo);
                var y = time.getFullYear();
                var m = time.getMonth() + 1;
                var d = time.getDate();
                return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ';
            },

            //将男女改为数字
            sexToText(data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].sex) {
                        data[i].sex = '男'
                    } else {
                        data[i].sex = '女'
                    }
                    data[i].entryTime = this.format(data[i].entryTime);
                    this.index.push(data[i].id)
                }
            },

            //渲染页面
            xr() {
                this.$axios({
                    url: '/teacher/list',
                    params: {
                        page: this.currentPage,
                        limit: 10
                    }
                }).then((res) => {
                    if (res.data == '') {
                        this.$router.push('/noResponse');
                    } else {
                        var data = res.data.data.list;
                        this.sexToText(data);
                        this.tableData = res.data.data.list;
                        this.pagenum = res.data.data.total;
                    }
                });

            },

            //渲染部门列表
            departmentList() {
                this.$axios({
                    url: '/teacher/findAllDepartment',
                    method: 'post'
                }).then((res) => {
                    var data = res.data.data;
                    for (var i = 0; i < data.length; i++) {
                        this.options1.push({value1: data[i].id, label1: data[i].departmentName})
                    }
                });
            },

        },

        //渲染表格数据、部门列表
        mounted() {
            this.xr();
            this.departmentList();
        }
    }
</script>

<style scoped lang="less">
    @fontcolor: #333;
    @contentbgcolor: white;

    #box1 {
        a {
            text-decoration: none;
            color: #333333;
        }

        li {
            list-style: none;
        }

        #box {
            background: #D3DCE6;
        }

        #el-popover-1715 {
            width: 500px;
        }

        .right {
            float: right;
            margin-right: 10px;;
        }

        .headerbox {
            margin-top: 20px;

            button, div {
                float: left;
                margin-left: 10px;
            }

            .right {
                float: right;
            }
        }

        .el-header {
            background-color: white;
            color: @fontcolor;
            line-height: 60px;
            font-size: 20px;
        }


        .el-header {
            margin-top: 10px;
            text-align: left;
        }


        .el-main {
            margin-top: 10px;
            background-color: @contentbgcolor;
            color: @fontcolor;
            text-align: center;
        }


        .el-dropdown-link {
            cursor: pointer;
            color: #409EFF;
        }


        .el-icon-arrow-down {
            font-size: 12px;
        }


        .el-pagination {
            float: right;
        }

        .opt {
            margin-left: 0;
        }
    }

    #box2 {
        @contentbgcolor: white;
        @margin: 10px;

        ul {
            padding: 0;
        }

        a {
            text-decoration: none;
            color: #333333;
        }

        li {
            list-style: none;
            margin-top: 15px;

            p {
                margin: 0;
            }

            #upload {
                width: 178px;
                height: 178px;
                border: 1px dashed #6b6767;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }

            .avatar-uploader .el-upload {
                border: 1px dashed #cfa1a1;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
            }

            .avatar-uploader .el-upload:hover {
                border-color: #409eff;
            }

            .avatar-uploader-icon {
                font-size: 28px;
                color: #587397;
                width: 178px;
                height: 178px;
                line-height: 178px;
                text-align: center;
            }

            .avatar {
                width: 178px;
                height: 178px;
                display: block;
            }
        }

        #box {
            background: #f2f2f6;
        }

        .el-container {
            margin: 0;
            padding: 0;
        }

        .el-header {
            margin-top: 20px;
            background-color: @contentbgcolor;
            color: #333;
            text-align: left;
            line-height: 60px;
            font-size: 20px;

            .right {
                float: right;
                margin-right: 10px;
            }
        }

        #content {
            background: @contentbgcolor;
            margin-top: 10px;

            .jiben {
                margin-left: 10px;
            }

            .left {
                float: left;
                margin-left: @margin;

                .img {
                    width: 150px;
                    height: 150px;
                    border-radius: 50%;

                    img {
                        width: 100%;
                        height: 100%;
                        border-radius: 50%;
                    }
                }

                .el-upload {
                    .el-button {
                        margin-left: 35px;
                        margin-top: 5px;
                    }
                }
            }

            .right {
                float: right;
                margin-right: @margin;

            }

            .el-input, .el-select {
                width: 750px;
                height: 50px;
            }
        }

        #footBox {
            width: 100%;
            height: 350px;
            background: white;
        }

        #footer {
            margin-left: 43%;
            height: 200px;

            .el-button {
                float: left;
                margin-top: 100px;
            }
        }

    }
</style>